package it.xiuxian.personcenter.fragment



import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.Color
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import com.afollestad.materialdialogs.MaterialDialog
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType.*
import com.tbruyelle.rxpermissions2.RxPermissions
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import it.xiuxian.lib.base.ArouterAddress
import it.xiuxian.lib.base.BaseFragment
import it.xiuxian.lib.bean.NewPersonBean
import it.xiuxian.lib.utils.*
import it.xiuxian.personcenter.R
import it.xiuxian.personcenter.bean.Constant
import it.xiuxian.personcenter.bean.ImageBean
import it.xiuxian.personcenter.bean.ShiMIngBean
import it.xiuxian.personcenter.databinding.FragmentPersoncenterBinding
import it.xiuxian.personcenter.presenter.PersonCenterFragmentPresenter
import it.xiuxian.personcenter.util.GlideEngine
import java.io.File


@Route(path = ArouterAddress.PERSONCENTERFRAGMENT)
class PersonCenterFragment:BaseFragment<PersonCenterFragmentPresenter>(){
    // APP_ID 替换为你的应用从官方网站申请到的合法appID
    private val APP_ID = "wxf58b045a6e5b7f2b"

    // IWXAPI 是第三方app和微信通信的openApi接口
    private var api: IWXAPI? = null
   lateinit var binding: FragmentPersoncenterBinding
    override val layoutId: Int
        get() = R.layout.fragment_personcenter
    override val presenter: PersonCenterFragmentPresenter
        get() = PersonCenterFragmentPresenter()

    override fun isEmpty(textView: TextView?): Boolean{
        return false
    }
    private fun isWXAppInstalledAndSupported(): Boolean{
        api = WXAPIFactory.createWXAPI(requireActivity(), APP_ID, true)
        api!!.registerApp(Constant.APP_ID)
        return api!!.isWXAppInstalled

    }
        @SuppressLint("CheckResult")
        fun selectPic(){
            RxPermissions(requireActivity())
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(io.reactivex.functions.Consumer<Boolean> { granted: Boolean ->
                    if (granted) {
                        PictureSelector.create(this)
                            .openGallery(ofImage())
                            .previewImage(true)
                            .loadImageEngine(GlideEngine.createGlideEngine())
                            .isCamera(true)
                            .imageFormat(PNG_Q)
                            .maxSelectNum(1)
                            .compress(true)
                            .forResult(PictureConfig.CHOOSE_REQUEST)

                    }
                })

        }

    override fun onHiddenChanged(hidden: Boolean){
        super.onHiddenChanged(hidden)
        if(!hidden){
            mPresenter!!.getHomePage()
        }
    }


    override fun initView(){
        //super.initView()
        ARouter.getInstance().inject(this)
        //LogUtils.e("personcenter被加载",Throwable())
        //ToastUtil.showShort("personcenter被加载了")
        binding= getViewDataBinding<FragmentPersoncenterBinding>()
        LiveDataBus.get().with(RxBusCode.FACE).observe(this, Observer {
            loadData()
        })


        binding.imageview.setOnClickListener {
            ARouter.getInstance().build(ArouterAddress.SETTINGACTIVITY).withString("qianming",qianming).withString("phone",phone).withString("nickname",nickName).navigation()
        }
        //实名
        binding.llGongzuozheng.setOnClickListener{
            if(is_real==1){
               mPresenter!!.getShiming()
               // ToastUtil.showShort("已经实名")
            }else{ARouter.getInstance().build(ArouterAddress.SHIMINGACTIVITY).navigation()
                if(weixinstate=="2"){
                    if(isWXAppInstalledAndSupported()){

                        // send oauth request
                        var req =  SendAuth.Req();
                        req.scope = "snsapi_userinfo";
                        req.state = "none";
                        api!!.sendReq(req);

                    } else {
                        ToastUtil.showShort("用户没有安装微信")
                    }
                }else if(weixinstate=="1"){
                    ARouter.getInstance().build(ArouterAddress.SHIMINGACTIVITY).navigation()
                }

                //ARouter.getInstance().build(ArouterAddress.SHIMINGACTIVITY).navigation()
                //ARouter.getInstance().build(ArouterAddress.QIANDAOACTIVITY).navigation()
            }

        }
        //日志
        binding.llRizhi.setOnClickListener {
            if(Utils.isFastClick()){
                ARouter.getInstance().build(ArouterAddress.RECORDDETAILACTIVITY).navigation()
            }

        }
        binding.llDingdan.setOnClickListener {
            ARouter.getInstance().build(ArouterAddress.ZHUXIAOACTIVITY).navigation()
        }
        binding.llWallet.setOnClickListener {
            ARouter.getInstance().build(ArouterAddress.MYWALLETACTIVITY).navigation()
        }
        binding.llYaoqinghaoyou.setOnClickListener {
            if(Utils.isFastClick()){
                ARouter.getInstance().build(ArouterAddress.INVITEFRIENDSACTIVITY).withString("erweima",erweima).withString("yaoqingma",yaoqingma).navigation()
            }
        }
        binding.llKefu.setOnClickListener{
            ARouter.getInstance().build(ArouterAddress.ABOUTUSACTIVITY).navigation()
        }
        binding.llGongyou.setOnClickListener {
            ARouter.getInstance().build(ArouterAddress.MYTEAMACTIVITY).withString("erweima",erweima).withString("yaoqingma",yaoqingma).navigation()
        }

        binding.image.setOnClickListener {
            if(Utils.isFastClick()){
                selectPic()

            }

        }
        binding.llGongyichi.setOnClickListener {
            ARouter.getInstance().build(ArouterAddress.GONGXIANACTIVITY).navigation()
        }
        binding.llGonggao.setOnClickListener {
            ARouter.getInstance().build(ArouterAddress.GONGGAOACTIVITY).navigation()
        }
        binding.llChengzhangzhi.setOnClickListener { ARouter.getInstance().build(ArouterAddress.CHENGZHANGZHIACTIVITY).withString("chengzhangzhi",chengzhangzhi).navigation() }
        binding.llGongxianzhi.setOnClickListener {ARouter.getInstance().build(ArouterAddress.GONGXIANZHIACTIVITY).navigation()}
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

  private lateinit var filePath: String

     override fun onActivityResult(
         requestCode: Int,
         resultCode: Int,
         data: Intent?
     ): Unit {
         super.onActivityResult(requestCode, resultCode, data)
        /* if (requestCode == WMToolImage.ALBUM_CHOOSE && resultCode == RESULT_OK) {
           var mSelected = Matisse.obtainResult(data)
           var i=  mSelected[0]
             Log.d("Matisse", "mSelected: $mSelected")
            var uri= UriUtils.getRealFilePath(requireActivity(),i!!)
             Log.d("Matisse", "mSelected: $uri")
             mPresenter!!.onload(File(uri))

         }*/
          if (resultCode == RESULT_OK) {
              when (requestCode) {
                  PictureConfig.CHOOSE_REQUEST -> {
                      val selectList = PictureSelector.obtainMultipleResult(data)
                      val media = selectList[0]
                      if (media.isCompressed) {
                          filePath = media.compressPath
                      } else {
                          filePath = media.path
                      }
                      Log.e("PictureConfig","filepath路径:"+filePath)
                      mPresenter!!.onload(File(filePath))
                  }
              }
          }
     }
    override fun loadData(){
        mPresenter!!.getHomePage()
    }
   /*public override fun initData() {

    }*/
    private var is_real:Int?=null
    private var userId:String?=null
    private var phone:String?=null
    private var nickName:String?=null
    private var qianming:String?=null
    private var erweima:String?=null
    private var yaoqingma:String?=null
    private var weixinstate:String?=null
    private var face:String?=null
    lateinit var chengzhangzhi:String
    fun setUI(userMsg: NewPersonBean){
        Log.e("person",userMsg.toString())
        binding.tvName.text = userMsg.nickname
       // binding.tvDengji.text = userMsg.dengjiname
        binding.tvChengzhang.text =userMsg.chengchangzhi
        binding.tvId.text = "ID: "+userMsg.usercode
        chengzhangzhi = userMsg.chengchangzhi
        binding.tvWallet.text = userMsg.money
        binding.tvGongxianzhi.text = userMsg.gongxianzhi
        is_real = userMsg.shimingstate
        userId = userMsg.id
        phone= userMsg.userphone
        nickName = userMsg.nickname
        qianming = userMsg.qianming
        yaoqingma = userMsg.yaoqingma
        erweima = userMsg.yaoqingerweima
        weixinstate =userMsg.wechatstate
        face = userMsg.faceurl
       /* if(userMsg.shimingstate==1){

        }*/
        Glide.with(this).applyDefaultRequestOptions(
            RequestOptions().skipMemoryCache(true).diskCacheStrategy(
            DiskCacheStrategy.NONE).circleCrop()).load(userMsg.faceurl).into(binding.image)

    }

    fun updata(data: ImageBean){
        Log.e("person",data.toString())
        mPresenter!!.getHomePage()
        Glide.with(this).applyDefaultRequestOptions(
            RequestOptions().skipMemoryCache(true).diskCacheStrategy(
                DiskCacheStrategy.NONE).circleCrop()).load(data.url).into(binding.image)
    }

    fun setShiMing(data: ShiMIngBean){
        var dialog1 =  MaterialDialog.Builder(requireActivity())
        var dialog = dialog1.customView(R.layout.activity_alert_gongzuozheng,false)
            .autoDismiss(true)
            .cancelable(true)
            .show()
        var customView: View = dialog!!.getCustomView()!!
        (customView.parent as ViewGroup).setBackgroundColor(Color.TRANSPARENT)
        (customView.parent.parent as ViewGroup).setBackgroundColor(Color.TRANSPARENT)
        (customView.parent.parent.parent as ViewGroup).setBackgroundColor(Color.TRANSPARENT)
        (customView.parent.parent.parent.parent as ViewGroup).setBackgroundColor(Color.TRANSPARENT)
        (customView.parent.parent.parent.parent.parent as ViewGroup).setBackgroundColor(
            Color.TRANSPARENT
        )
        Glide.with(this).applyDefaultRequestOptions(
            RequestOptions().skipMemoryCache(true).diskCacheStrategy(
                DiskCacheStrategy.NONE).circleCrop()).load(data.faceurl).into(customView.findViewById<ImageView>(R.id.image))
        customView.findViewById<TextView>(R.id.tv_name).text = data.name
        customView.findViewById<TextView>(R.id.tv_id).text = data.idcard
        Glide.with(this).applyDefaultRequestOptions(
            RequestOptions().diskCacheStrategy(
                DiskCacheStrategy.NONE).skipMemoryCache(true)).load(erweima).into(customView.findViewById<ImageView>(R.id.image_haoyou))
        // RichText.from(data.notice.message).into(customView.findViewById<TextView>(R.id.tv_content))
        customView.findViewById<ImageView>(R.id.ivClose).setOnClickListener {
            dialog.dismiss()
        }
    }


}